<template>
    <div class="fillcontain">
        <!-- <head-top></head-top> -->
        <div class="table_container" >
            <el-row :gutter="20">
                <el-col :span="10">
                    <div class="demo-input-suffix" >
                        <el-tree :data="treeLists" node-key="id" ref="treelist" highlight-current
                                :props="defaultProps" @node-click="handleNodeClick">
                        </el-tree>                                                                               
                    </div>

                </el-col>
                <el-col :span="14" >
                  <div class="demo-input-suffix">
                    <el-form :model="selectTable" :rules="rules" ref="editForm">
                        <el-form-item label="编码" label-width="100px" prop="code">
                            <el-input v-model="selectTable.code" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="名称" label-width="100px" prop="name">
                            <el-input v-model="selectTable.name" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label=" " label-width="100px">
                           <el-checkbox v-model="bmjbj">末级标记</el-checkbox>  
                        </el-form-item>                                                      
    
                    </el-form>
                  </div>
                  <div style="text-align:left">
                    <el-button-group>
                        <el-button type="primary" :disabled="bEdit" ref="btnAddChild" icon="el-icon-edit" @click="doAddChild()">添加子节点</el-button>
                        <el-button type="primary" :disabled="bEdit" icon="el-icon-share" @click="doAddBrother()">添加同级节点</el-button>
                        <el-button type="primary" :disabled="bEdit" icon="el-icon-edit" @click="doModify()">修改</el-button>
                        <el-button type="primary" :disabled="!bEdit" icon="el-icon-plus" @click="doSaveSpfl()">保存</el-button> 
                        <el-button type="primary" :disabled="!bEdit" icon="el-icon-close" @click="doCancel()">取消</el-button>
                        <el-button type="primary" icon="el-icon-delete" :disabled="bEdit" @click="doDelete()">删除</el-button>
                    </el-button-group>
                  </div>
                </el-col>
            </el-row>    
 
        </div>
         
    </div>
</template>

<script>
    import headTop from '../components/headTop'
    import {baseUrl, baseImgPath} from '@/config/env'
    import {getspflLists,getspflOne,saveSpfl,deleteSpfl} from '@/api/getData'
    export default {
        data(){
            return {
                baseUrl,
                baseImgPath,
                bADD:true,  //添加模式
                searchLoading:false,
                activeNames: ['1'],
                status:'',
                zlclfs:'',
                treeLists:[],  
                typeLists:[{
                    value: '0',
                    label: '正常1'
                    }, {
                    value: '1',
                    label: '停用2'
                    }
                ],                
                bEdit:false, 
                editMode :2,  // 0 //加下级节点 1 加同级节点 2 修改
                currentData:null,
                selectIndex: null,
                city: {},
                offset: 0,
                limit: 20,
                count: 0,
                tableData: [],
                currentPage: 1,
                selectTable: {},
                dialogFormVisible: false,
                categoryOptions: [],
                selectedCategory: [],
                address: {},
                skfsname:'',
                mallname:'',
                defaultProps: {
                children: 'children',
                label: 'label'
                },
               // bjf :true,
                bmjbj :false,
                rules : {
                    name : [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ],
                    code : [
                        { required: true,  message: '请输入编码', trigger: 'blur' }
                    ]
                },
         
            }
        },
        created(){
            this.initData();
        },
    	components: {
    		headTop,
    	},
        methods: {
            async initData(){
                try{
                    this.getspflLists();
                }catch(err){
                    console.log('获取数据失败', err);
                }
            },
            
            async getspflLists(){
                const {latitude, longitude} = this.city;
                var _this = this
                var data = {
                    page:_this.currentPage,
                    rows:_this.limit
                }
                const skfslist = await getspflLists(data);
                this.treeLists = [];
               // _this.treeLists = skfslist.rows 
                    skfslist.forEach(item => {
                    const tableData = {};
                    tableData.id = item.id;
                    tableData.label = item.label;
                    tableData.children = item.children;
                    
                    this.treeLists.push(tableData);
                }) 
                //console.log('treelist',this.treeLists)  
            },   
            async getspflOne(){
                var _this = this
                var data = {
                    id:_this.currentData.id
                }
                const oneShop = await getspflOne(data);
                if(oneShop.Status==0){
                    if(this.editMode==0){  //如果是加下级节点
                        //this.selectTable.id = oneShop.data.id
                        this.selectTable.fid = oneShop.data.id
                    }else if(this.editMode==1){ //如果加同级节点
                        this.selectTable.fid = oneShop.data.fid
                    }else{    //如果是修改
                        this.selectTable.id = oneShop.data.id
                        this.selectTable.fid = oneShop.data.fid                       
                    }
                    _this.selectTable.code = oneShop.data.code
                    _this.selectTable.name = oneShop.data.name
                    _this.selectTable.mjbj = oneShop.data.mjbj
                    
                   // this.selectTable.bmjbj = (oneShop.data.mjbj==1)?true:false
                    _this.bmjbj = (oneShop.data.mjbj==1)?true:false
                    _this.SetControlStatus(true)
                }else{
                    this.$message({
                        type: 'error', 
                        message: '获取商品分类信息失败'
                    });                   
                }
               // console.log('selectTable',this.selectTable)  
            },                   
            handleNodeClick(data) {
                console.log(data.label);
                this.currentData = data
            }, 
            SetControlStatus(val) {
               //  this.$refs.btnAddChild.disabled=val
                 this.bEdit = val
                 if(val==false){
                     this.selectTable={}
                 }
            },                         
            doAddChild(){
               // this.SetControlStatus(true)
                this.editMode=0;
                this.getspflOne();
            },  
            doAddBrother(){
               // this.SetControlStatus(true)
                this.editMode=1;
                this.getspflOne();
            },               
            doCancel(){
                this.SetControlStatus(false)
               // this.selectTable={}
            }, 
            doModify(){
                this.editMode=2;
                this.getspflOne();
                console.log('111:',this.selectTable)
            },  
            doDelete(){
                //this.editMode=2;
                if(this.currentData==null){
                    this.$message({
                        type: 'error', 
                        message: '请选择要删除的商品分类'
                    });           
                    return;
                }
                this.doDeleteSpfl(this.currentData.id);
               // console.log('111:',this.selectTable)
            },                                                                
            doSaveSpfl(){ 
                try{
                    this.$refs['editForm'].validate( async (valid) => {
                        if (valid) {
                            console.log('submit!!',this.selectTable);
                           // this.selectTable.mjbj = (this.selectTable.bmjbj==true)?1:0;
                            this.selectTable.mjbj = (this.bmjbj==true)?1:0;
                            const res =  await saveSpfl(this.selectTable)
                           // console.log('res',res)
                            if (res.Status == 0) {
                                this.$message({
                                    type: 'success',
                                    message: '保存商品分类成功'
                                });
                                this.selectTable.id = res.ret.id
                                console.log('editMode',this.editMode)  
                               // this.$refs.treelist.getCurrentNode.label  = this.selectTable.name
                               if(this.editMode==2){
                                  //  console.log('editMode',this.editMode)
                                    console.log('selectTable',this.selectTable)
                                    this.updateDataToTree(this.treeLists,this.selectTable.id,this.selectTable)
                               }else if(this.editMode==0){
                                    console.log('selectTable0',this.selectTable)  
                                    this.setDataToTree(this.treeLists,this.selectTable.fid,this.selectTable)
                               }else{
                                    this.setDataToTree(this.treeLists,this.selectTable.fid,this.selectTable)
                               }
                               this.SetControlStatus(false) 
                               // this.getskfsLists();
                            }else{
                                this.$message({
                                    type: 'error', 
                                    message: res.msg
                                });
                            }                         
                        } else {
                            console.log('error submit!!');
                            return;
                        }
                    });

                }catch(err){
                    console.log('保存商品分类失败', err);
                    this.$message({
                        type: 'error',
                        message: '保存商品分类失败'
                    });
                }
            },
            doDeleteSpfl(id) {
                var idList = []
                idList[0] = id   
/*                 if(row.bj_used==1){
                    this.$alert('该收款方式已经使用,不能删除!', '注意', {
                        confirmButtonText: '确定',
                        callback: action => {
                            this.$message({
                            type: 'info',
                            message: `删除失败`
                            });
                        }
                    });
                    return;
                }    */          
                this.$confirm('此操作将删除该商品分类信息, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async() => {
                        const res = await deleteSpfl(idList);
                        if (res.Status == 0) {
                            this.$message({
                                type: 'success',
                                message: '删除商品分类成功'
                            });
                            this.deleteLocalDep(this.treeLists, id);
                        }else{
                            throw new Error(res.msg)
                        }
                    }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '取消删除'
                    });          
                });
            },            
            updateDataToTree(treeData,pId,respData){
               // console.log('treeData:',treeData)
                for(var i=0;i<treeData.length;i++) {
                    var td = treeData[i];
                   // console.log('td:',td)
                    if(td.id==pId) {
                        treeData[i].label='('+respData.code+')'+respData.name;
                       // break;
                        return;
                    }else{
                        //console.log('treeData:',treeData)
                        if(td.children){
                            this.updateDataToTree(td.children, pId, respData);
                        } 
                    }
                }
            },            
            setDataToTree(treeData,pId,respData){
                const newnode = {id:respData.id,label:'('+respData.code+')'+respData.name}
                for(var i=0;i<treeData.length;i++) {
                    var td = treeData[i];
                    if(td.id==pId) {
                    treeData[i].children=treeData[i].children.concat(newnode);
                    return;
                    }else{
                        if(td.children){
                            this.setDataToTree(td.children, pId, respData);
                        }
                    }
                }
            },
            deleteLocalDep(treeData,id){
                for(var i=0;i<treeData.length;i++) {
                    var td = treeData[i];
                    if(td.id==id) {
                        treeData.splice(i, 1);
                        return;
                    }else{
                      this.deleteLocalDep(td.children, id);
                    }
                }
            }            
        },
    }
</script>

<style lang="less">
	@import '../style/mixin';
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .table_container{
        padding: 10px 20px;
    }
    .Pagination{
        display: flex;
        justify-content: flex-start;
        margin-top: 8px;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }
    .avatar {
        width: 120px;
        height: 120px;
        display: block;
    }
    .demo-input-suffix {
        margin-bottom: 15px;
    }
    .demo-input.demo-zh-CN .el-input {
        width: 180px;
    }
    
    .demo-input-suffix .el-input {
        margin-right: 15px;
        width:auto
    }


</style>
